#coding=utf8

import urllib, BeautifulSoup

header = "#请不要在下面边添加任何条目，否则将在下次更新时失效！\n"

web=urllib.urlopen("http://www.360kb.com/kb/2_122.html")
soup=BeautifulSoup.BeautifulSoup(web.read())
new=soup.find(id="storybox")("p")[-1]
new_content=header+str(new).replace("&nbsp;",' ').replace("<br />","")[5:-5]

''' 备用方案
web=urllib.urlopen("http://git.oschina.net/jiange1236/googlehosts/raw/master/hosts141218.txt")
new_content=header+web.read()
'''

hosts=open("C:\Windows\System32\drivers\etc\hosts",'r')
old_content=hosts.read()
hosts.close()

hosts=open("C:\Windows\System32\drivers\etc\hosts",'w')
if old_content.find(header)<0:
    if old_content[-1]!='\n\n\n':
        content=old_content+'\n\n\n'+new_content
    else:
         content=old_content+new_content
else:
    old_content=old_content[:old_content.find(header)]
    content=old_content+new_content
content=unicode(content,"utf8").encode("gb2312")
hosts.write(content)
hosts.close()

print u"更新成功"
raw_input()